package com.martin.iconparse;

import android.text.TextUtils;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhangyang on 2018/3/28.
 */

public class Utils {

    private static final String TAG = "martin";

    private static final String USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.3 Mobile/14E277 Safari/603.1.30";

    /**
     * Log 每次的日志长度限制
     */
    private static final int LOG_LIMIT_SIZE = 4000;

    /**
     * 正则匹配 head
     */
    private static final String REGX_HEAD = "<head>.*</head>";

    /**
     * 正则匹配  rel="apple-touch-icon**
     */
    private static final String REGX_REL = "<link[^>]+rel=\"apple-touch-icon[\\S]+\"[^>]+>";

    /**
     * 正则匹配获取 href
     */
    private static final String REGX_HREF = "href=\"[^\"]*\"";

    /**
     * href 的头
     */
    private static final String HREF = "href=\"";

    private static EventParseProcess mEventProcess;

    /**
     * 获取指定 url 的网页源代码
     *
     * @param urlPath
     */
    public static String getIconByUrl(final String urlPath) {

        if (!isUrlRight(urlPath)) {
            log("url is wrong !");
            return null;
        }

        log("start to get html content form url:" + urlPath);

        try {
            URL url = new URL(urlPath);

            URLConnection urlConnection = url.openConnection();

            urlConnection.addRequestProperty("User-Agent", USER_AGENT);

            urlConnection.setConnectTimeout(5000);

            urlConnection.setReadTimeout(5000);

            //从流里读取网页源代码数据
            String source = readDataFromInputStream(urlConnection.getInputStream());

//            log("source:" + source);

            long startParseTime = System.currentTimeMillis();

            log("start to parse html content... startTime:" + startParseTime);

            //正则匹配 head 节点内容
            String headSource = matchString(source, REGX_HEAD);

//            log("headSource:" + headSource);

            //开始解析 head 节点内容，获取 icon url
            String iconUrl = parseIconFromHead(headSource);

            log("parse cost time:" + (System.currentTimeMillis() - startParseTime) + " ms");

            log("iconUrl:" + iconUrl);

            return iconUrl;

        } catch (Exception e) {
            log(e.getMessage());
        }
        return null;
    }


    /**
     * 解析 head 内容，获取图片 url
     *
     * @param source
     */
    private static String parseIconFromHead(String source) {
        String iconStr = matchString(source, REGX_REL);
        if (TextUtils.isEmpty(iconStr)) {
            log("can not find rel=apple-touch-iconXXX");
            return "";
        }

//        log("iconStr:" + iconStr);
        String hrefStr = matchString(iconStr, REGX_HREF);
        if (TextUtils.isEmpty(hrefStr)) {
            log("can not fid href ...");
            return "";
        }

//        log("href:" + hrefStr);
        String iconUrl = hrefStr.substring(HREF.length(), hrefStr.length() - 1);
        if (!iconUrl.startsWith("https") && !iconUrl.startsWith("http")) {
            iconUrl = "http://" + iconUrl;
        }

        return iconUrl;
    }

    /**
     * 正则匹配，并返回匹配结果(NOTE:单行模式，并且只会返回第一个寻找到的)
     *
     * @param source
     * @param regx
     * @return
     */
    private static String matchString(String source, String regx) {
        Pattern pattern = Pattern.compile(regx, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            return matcher.group();
        }
        return "";
    }

    /**
     * 读取 InputStream 获取 byte 数组
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    private static String readDataFromInputStream(InputStream inputStream) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        StringBuffer sb = new StringBuffer();
        String data = null;
        while ((data = br.readLine()) != null) {
            sb.append(data);
        }
        return sb.toString();
    }

    /**
     * 判断网址是否合法
     *
     * @param url
     * @return
     */
    private static boolean isUrlRight(String url) {
        if (TextUtils.isEmpty(url)) {
            log("url is null or empty !");
            return false;
        }
        URI uri = null;
        try {
            uri = new URI(url);
        } catch (Exception e) {
            return false;
        }
        if (uri.getHost() == null) {
            return false;
        }

        if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) {
            return false;
        }

        return true;
    }



    /**
     * 打印 log 信息
     *
     * @param log
     */
    public static void log(String log) {

        //Event 通知进度
        if(mEventProcess == null){
            mEventProcess = new EventParseProcess();
        }
        mEventProcess.setShowInfo(log);
        EventBus.getDefault().post(mEventProcess);

        if (log.length() > LOG_LIMIT_SIZE) {

            for (int i = 0; i < log.length(); i += LOG_LIMIT_SIZE) {
                if (i + LOG_LIMIT_SIZE < log.length()) {
                    Log.d(TAG, log.substring(i, i + LOG_LIMIT_SIZE));
                } else {
                    Log.d(TAG, log.substring(i, log.length()));
                }
            }

        } else {

            Log.d(TAG, log);

        }
    }

}
